package com.offcn.utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //解决请求响应中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String way = request.getParameter("way");
        //获取请求地址
        String requestURI = request.getRequestURI();
        //注册登录这样的界面可以直接放行
        if(
                requestURI.equals(request.getContextPath()+"/index.jsp")||requestURI.equals(request.getContextPath()+"/login.jsp") ||
                        requestURI.contains(request.getContextPath()+"/static")||
                requestURI.equals(request.getContextPath()+"/regist.jsp")||
                (requestURI.equals(request.getContextPath()+"/UserServlet")&&way.equals("doLogin"))||
                (requestURI.equals(request.getContextPath()+"/UserServlet")&&way.equals("doRegist"))||
                        (requestURI.equals(request.getContextPath()+"/UserServlet")&&way.equals("checkUser"))||
                        requestURI.contains(request.getContextPath()+"/js")
        ){
            //不用登录就可以访问的请求，直接放行
            chain.doFilter(req, resp);
        }else{
            //需要登录或者注册成功才可以访问的  登陆成功时会在session中存入user对象,注册成功会存入username(可以进入注册成功界面)
            if(request.getSession().getAttribute("user")!=null || request.getSession().getAttribute("username")!=null){
//                说明是登陆成功的，可以放行
                chain.doFilter(req, resp);
            }else{
                //没有登陆，驳回请求，调回登录界面,提示先登录
                request.getSession().setAttribute("errorMsg","请先登录");
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }


    }

}
